import React, { useEffect, useState } from 'react'
import PubSub from 'pubsub-js'
import { getUser } from '../api/user';

export default function Main() {
    // 定义状态数据
    let [users, setUsers] = useState([])
    let [loading, setLoading] = useState(false)
    let [first, setFirst] = useState(true)
    useEffect(() => {
        let SearchId = PubSub.subscribe('search', async (msg, uname) => {
            // 用来判读是否为第一次进入界面
            first && setFirst(false)
            // 当按下搜索键时，改变当前的状态为true
            setLoading(true)
            console.log(uname);
            let {items} = await getUser(uname)  
            setUsers(items)
            // 请求到数据后，去除loading状态
            setLoading(false)
        })
        return () => {
            PubSub.unsubscribe(SearchId) // 取消订阅

        }
    }, )
    if(first){
        return <h3>请输入用户名搜索</h3>
    }

    if(loading) {
        return <h2>Loading...</h2>
    }
  return (
    <div>
       <div className="row">
        {users.map(user => 
            <div className="card" key={user.id}>
                <a href={user.html_url} target="_blank" rel="noreferrer">
                <img src={user.avatar_url} alt="" style={{width: 100}} />
                </a>
                <p className="card-text">{user.login}</p>
            </div>
        )}
            
            
        </div>
    </div>
  )
}
